// The MIT License
// 
// Copyright (c) 2008 Werner Strydom
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import "MetaWeblogPlugIn.h"


@implementation MetaWeblogPlugIn

 - (id)initWithAPIManager:(id<PROAPIAccessing>)apiManager
{
	if (self = [super init])
	{
		_apiManager	= apiManager;
		_exportManager = [[_apiManager apiForProtocol:@protocol(ApertureExportManager)] retain];
		if (!_exportManager)
			return nil;
		
		_progressLock = [[NSLock alloc] init];
	}
	return self;
}

- (void)dealloc
{
	
	[_topLevelNibObjects makeObjectsPerformSelector:@selector(release)];
	[_topLevelNibObjects release];
	
	[_progressLock release];
	[_exportManager release];
	
	[super dealloc];
}


#pragma mark -
// UI Methods
#pragma mark UI Methods

- (NSView *)settingsView
{
	if (nil == settingsView)
	{
		// Load the nib using NSNib, and retain the array of top-level objects so we can release
		// them properly in dealloc
		NSBundle *myBundle = [NSBundle bundleForClass:[self class]];
		NSNib *myNib = [[NSNib alloc] initWithNibNamed:@"MetaWeblogPlugIn" bundle:myBundle];
		if ([myNib instantiateNibWithOwner:self topLevelObjects:&_topLevelNibObjects])
		{
			[_topLevelNibObjects retain];
		}
		[myNib release];
	}
	
	return settingsView;
}

- (NSView *)firstView
{
	return firstView;
}

- (NSView *)lastView
{
	return lastView;
}

- (void)willBeActivated
{	
	NSAutoreleasePool *pool =  [[NSAutoreleasePool alloc] init];
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSString* pluginIdentifier = [[[NSBundle bundleForClass: [self class]] infoDictionary] objectForKey: @"CFBundleIdentifier"];
	NSMutableDictionary* settings = [NSMutableDictionary dictionaryWithDictionary: [defaults persistentDomainForName:pluginIdentifier]];
	
	[blogAccessPointTextField setStringValue: [settings valueForKey: @"accessPoint"]];
	[blogIdTextField setStringValue: [settings valueForKey: @"blogId"]];
	[blogUserNameTextField setStringValue: [settings valueForKey: @"username"]];
	[blogPasswordTextField setStringValue: [settings valueForKey: @"password"]];
	
	[pool release];
}

- (void)willBeDeactivated
{	
}

#pragma mark
// Aperture UI Controls
#pragma mark Aperture UI Controls

- (BOOL)allowsOnlyPlugInPresets
{
	return TRUE;	
}

- (BOOL)allowsMasterExport
{
	return FALSE;	
}

- (BOOL)allowsVersionExport
{
	return TRUE;	
}

- (BOOL)wantsFileNamingControls
{
	return FALSE;	
}

- (void)exportManagerExportTypeDidChange
{	
}

#pragma mark -
// Save Path Methods
#pragma mark Save/Path Methods

- (BOOL)wantsDestinationPathPrompt
{
	return FALSE;
}

- (NSString *)destinationPath
{
	return nil;
}

- (NSString *)defaultDirectory
{
	return nil;
}


#pragma mark -
// Export Process Methods
#pragma mark Export Process Methods

- (void)exportManagerShouldBeginExport
{
	// create the blog instance
	_blog = [[MetaWeblog alloc] init];
	[_blog setUrl: [blogAccessPointTextField stringValue]];
	[_blog setBlogId: [blogIdTextField stringValue]];
	[_blog setUsername: [blogUserNameTextField stringValue]];
	[_blog setPassword: [blogPasswordTextField stringValue]];
		
	// save settings
	NSAutoreleasePool *pool =  [[NSAutoreleasePool alloc] init];
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSString* pluginIdentifier = [[[NSBundle bundleForClass: [self class]] infoDictionary] objectForKey: @"CFBundleIdentifier"];
	NSMutableDictionary* settings = [NSMutableDictionary dictionaryWithDictionary: [defaults persistentDomainForName:pluginIdentifier]];
	[settings setValue: [_blog url] forKey: @"accessPoint"];	
	[settings setValue: [_blog blogId] forKey: @"blogId"];	
	[settings setValue: [_blog username] forKey: @"username"];	
	[settings setValue: [_blog password] forKey: @"password"];	
	[defaults setPersistentDomain:settings forName:pluginIdentifier];	
	[defaults synchronize];
	[pool release];
	
	// initialize the progress
	unsigned long count = [_exportManager imageCount];
	[self lockProgress];
	// one for exporting the image, one for uploading it to the server, and one for creating the post
	exportProgress.totalValue = count * 3;
 	exportProgress.currentValue = 0;
	exportProgress.message = @"Exporting...";
	[self unlockProgress];	
	[_exportManager shouldBeginExport];
}

- (void)exportManagerWillBeginExportToPath:(NSString *)path
{
}

- (BOOL)exportManagerShouldExportImageAtIndex:(unsigned)index
{
	return TRUE;
}

- (void)exportManagerWillExportImageAtIndex:(unsigned)index
{
	
}

- (BOOL)exportManagerShouldWriteImageData:(NSData *)imageData toRelativePath:(NSString *)path forImageAtIndex:(unsigned)index
{
	NSAutoreleasePool *pool =  [[NSAutoreleasePool alloc] init];
	
	NSDictionary* properties = [_exportManager propertiesForImageAtIndex: index];
	NSString* versionName = [properties objectForKey:@"kExportKeyVersionName"];
	NSString* name = [path lastPathComponent];
	[self updateProgress: [NSString stringWithFormat: @"Uploading %@", versionName]];

	NSString* url = [_blog newMediaObject: name andType: @"image/jpeg" andBits: imageData];
	if(url != nil)
	{
		NSLog(@"Uploaded image %@", url);
			  
		Post* post = [[Post alloc] init];
		post.title = versionName;
		post.description = [NSString stringWithFormat: @"<img src=\"%@\" />", url];
		post.dateCreated = [NSCalendarDate init];
		
		[self updateProgress: [NSString stringWithFormat: @"Creating post for %@", versionName]];
		NSString* postId = [_blog newPost: post];
		NSLog(@"Created post with id %@", postId);
		
		[post release];
	}
	else
	{
		NSLog(@"Failed to upload the image '%@'", path);
	}
	
	[self updateProgress: @"Exporting..."];
	[pool release];
	return FALSE;	
}

- (void)updateProgress: (NSString*) msg
{
	[self lockProgress];
	[msg retain];
	exportProgress.currentValue += 1;
	exportProgress.message = msg;
	[self unlockProgress];	
}

- (void)exportManagerDidWriteImageDataToRelativePath:(NSString *)relativePath forImageAtIndex:(unsigned)index
{
}

- (void)exportManagerDidFinishExport
{
	[_blog release];
	_blog = nil;
	[_exportManager shouldFinishExport];
}

- (void)exportManagerShouldCancelExport
{
	[_blog release];
	_blog = nil;
	[_exportManager shouldCancelExport];
}


#pragma mark -
	// Progress Methods
#pragma mark Progress Methods

- (ApertureExportProgress *)progress
{
	return &exportProgress;
}

- (void)lockProgress
{
	
	if (!_progressLock)
		_progressLock = [[NSLock alloc] init];
		
	[_progressLock lock];
}

- (void)unlockProgress
{
	[_progressLock unlock];
}

@end
